package com.xbq.exceleditor.ui.filechooser

import android.app.Activity
import android.content.Intent
import android.os.Bundle
import androidx.fragment.app.Fragment
import androidx.viewpager2.adapter.FragmentStateAdapter
import com.blankj.utilcode.util.ToastUtils
import com.google.android.material.tabs.TabLayout
import com.gyf.immersionbar.ktx.immersionBar
import com.xbq.exceleditor.R
import com.xbq.exceleditor.databinding.ActivityFileChooserBinding
import com.xbq.exceleditor.ui.filechooser.media.ContentResolveFile
import com.xbq.exceleditor.ui.filechooser.media.FileTypeEnum
import com.xbq.xbqsdk.component.activity.VBActivity
import com.xbq.xbqsdk.util.activityresult.ActivityResultCallback
import com.xbq.xbqsdk.util.activityresult.StartActivityForResultHelper
import com.xbq.xbqsdk.util.click.onDebouncedClick
import dagger.hilt.android.AndroidEntryPoint
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode
import java.io.File

/**
 * Author: liaohaiping
 * Time: 2021-06-30
 * Description:
 */
@AndroidEntryPoint
class FileChooserActivity :
    VBActivity<ActivityFileChooserBinding>() {
    val contentFragment by lazy { FileByContentResolverListFragment.newFragment(fileType!!) }
    val qqFileFragment by lazy {
        FileByExtensionListFragment.newFragment(
            fileType!!,
            FileByExtensionListFragment.DIR_TYPE_QQ
        )
    }
    val weixinFileFragment by lazy {
        FileByExtensionListFragment.newFragment(
            fileType!!,
            FileByExtensionListFragment.DIR_TYPE_WEIXIN
        )
    }
    val storageFileFragment by lazy { StorageFileFragment.newFragment(fileType!!) }
    var fileType: FileTypeEnum? = null
    var selectedFile: File? = null
    val fragments = mutableListOf<Fragment>()

    override fun useEventBus(): Boolean {
        return true
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        parseArguments()
        if (fileType == null) {
            finish()
            return
        }

        binding.adview.init("filechooser",this)
        immersionBar {
            statusBarView(binding.statusbar)
        }

        binding.btnBack.setOnClickListener { finish() }
        binding.btnSubmit.onDebouncedClick {
            if(selectedFile!=null){
                setResult(RESULT_OK,Intent().putExtra(EXTRA_RESULT_FILE,selectedFile!!))
                finish()
            }else{
                ToastUtils.showShort(R.string.pls_choose_file)
            }
        }


        fragments.add(contentFragment)
        fragments.add(weixinFileFragment)
        fragments.add(qqFileFragment)
        fragments.add(storageFileFragment)
        binding.viewPager.isUserInputEnabled =false
        binding.viewPager.offscreenPageLimit = fragments.size
        binding.viewPager.adapter = object : FragmentStateAdapter(this) {
            override fun getItemCount(): Int {
                return fragments.size
            }

            override fun createFragment(position: Int): Fragment {
                return fragments[position]
            }

        }
        binding.tabs.addOnTabSelectedListener(object : TabLayout.OnTabSelectedListener {
            override fun onTabSelected(tab: TabLayout.Tab?) {
                tab?.position?.let {
                    binding.viewPager.setCurrentItem(it, false)
                }
            }

            override fun onTabUnselected(tab: TabLayout.Tab?) {
            }

            override fun onTabReselected(tab: TabLayout.Tab?) {
            }

        })
    }

    fun parseArguments() {
        val fileTypeName = intent.getStringExtra(EXTRA_FILE_TYPE)
        fileTypeName?.let {
            this.fileType = FileTypeEnum.valueOf(it)
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onContentResolveFileRecevied(file: ContentResolveFile) {
        markSelectedFile(File(file.filePath))
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onExtFileRecevied(file: ExtFile) {
        markSelectedFile(file)
    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onFileRecevied(file: File) {
        markSelectedFile(file)
    }

    fun markSelectedFile(file:File?){
        selectedFile = file
        binding.btnSubmit.isEnabled = selectedFile!=null
    }


    companion object {
        const val EXTRA_FILE_TYPE = "EXTRA_FILE_TYPE"
        const val EXTRA_RESULT_FILE = "EXTRA_RESULT_FILE"
        fun startForResult(
            activity: Activity,
            fileType: FileTypeEnum,
            callback: ActivityResultCallback
        ) {
            val intent = Intent(activity, FileChooserActivity::class.java).apply {
                putExtra(EXTRA_FILE_TYPE, fileType.name)
            }
            StartActivityForResultHelper.startActivityForResult(activity, intent, callback)
        }

        fun getResult(intent:Intent):File?{
            val file = intent.getSerializableExtra(EXTRA_RESULT_FILE) as File?
            return file
        }

    }
}